using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine.UI;
using HashTable = ExitGames.Client.Photon.Hashtable;
using DG.Tweening;

public class Launcher : MonoBehaviourPunCallbacks
{
    public GameObject panel;     //获取登录面板
    public InputField roomName;     //获取用户输入的房间名
    public GameObject comparingPanel;   //匹配信息面板

    public Text player1Name;    //房主名称（红方）
    public Text player2Name;    //其他玩家名称

    #region 同步相关
    private int currPlayerCount = 0; //当前房间内的玩家数量
    public int CurrPlayerCount
    {
        get { return currPlayerCount; }
        set
        {
            currPlayerCount = value;
            if (currPlayerCount == 2)
            {
                isWaiting = false;
            }
        }
    }
    private bool isWaiting = true;   //用来在匹配界面等待双方玩家就绪

    HashTable LaunchTable = new HashTable();


    public override void OnRoomPropertiesUpdate(HashTable propertiesThatChanged)
    {
        if (PhotonNetwork.CurrentRoom.CustomProperties.ContainsKey("currPlayerCount"))
        {
            CurrPlayerCount = (int)propertiesThatChanged["currPlayerCount"];    //把网络中的值传回脚本
        }
        
    }
    #endregion

    #region 连接相关
    public void Start()
    {
        PhotonNetwork.ConnectUsingSettings();   //连接PUN服务器
        PhotonNetwork.AutomaticallySyncScene = true;
        LaunchTable.Add("currPlayerCount", CurrPlayerCount);
    }
    public override void OnConnectedToMaster()  //连接成功的回调函数
    {
        panel.SetActive(true);
    }
    #endregion

    #region 创建房间与进入游戏界面

    public Transform redInfo;   // 匹配面板
    public Transform blueInfo;

    public void LoginButtonClick()  //进入游戏按钮事件
    {
        if (roomName.text.Length <= 1)  //房间名字数不能太少
            return;
        panel.SetActive(true);

        RoomOptions roomOptions = new RoomOptions { MaxPlayers = 2 };
        PhotonNetwork.JoinOrCreateRoom(roomName.text, roomOptions, default);    //创建房间
    }
    public override void OnJoinedRoom() //创建房间回调函数，进入游戏匹配界面
    {
        comparingPanel.SetActive(true);

        #region 动画相关
        Tweener redTweener = redInfo.DOLocalMoveX(660, 1f);
        redTweener.SetEase(Ease.OutBounce);
        Tweener blueTweener = blueInfo.DOLocalMoveX(-660, 1f);
        blueTweener.SetEase(Ease.OutBounce);
        #endregion


        if (PhotonNetwork.InRoom)
        {
            Debug.Log("在房间里");
            if (PhotonNetwork.CurrentRoom.CustomProperties.ContainsKey("currPlayerCount"))
            {
                Debug.Log("哈希表里有这个currPlayerCount");
                CurrPlayerCount = (int)PhotonNetwork.CurrentRoom.CustomProperties["currPlayerCount"];
            }
        }
        CurrPlayerCount++;
        LaunchTable["currPlayerCount"] = CurrPlayerCount;
        PhotonNetwork.CurrentRoom.SetCustomProperties(LaunchTable);    // 同步当前房间内的人数

        StartCoroutine(LoadingComparingPenel());
    }
    IEnumerator LoadingComparingPenel()      //正式进入游戏
    {
        while (isWaiting)    // 房间内人没满就一直刷新双方信息UI
        {
            if (PhotonNetwork.IsMasterClient)   //房主是红方，也是玩家1
            {
                player1Name.text = PhotonNetwork.NickName;

                if (PhotonNetwork.CurrentRoom.Players.ContainsKey(2))   //填充玩家2的名字
                {
                    PhotonNetwork.CurrentRoom.Players.TryGetValue(2, out Photon.Realtime.Player player2);
                    player2Name.text = player2.NickName;
                }
            }
            //你若不是房主，那你就是玩家2
            else
            {
                PhotonNetwork.CurrentRoom.Players.TryGetValue(1, out Photon.Realtime.Player player1);   //填充玩家1的名字
                player1Name.text = player1.NickName;

                player2Name.text = PhotonNetwork.NickName;
            }

            yield return new WaitForSeconds(0.1f);  //每0.1s刷新一次UI
        }
        yield return new WaitForSeconds(3f);    //双方就绪后，留3s让玩家看信息
        PhotonNetwork.LoadLevel(1);
    }
    #endregion

}
